package com.mybatisPlus.springSecurity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatisPlus.dao.entity.User;
import com.mybatisPlus.dao.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("userDetail")
public class UserDetailsImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", s)
                .or()
                .eq("email", s)
                .or()
                .eq("phone_num", s);
        List<User> userList = userMapper.selectList(wrapper);
        if(userList.isEmpty()){
            throw  new UsernameNotFoundException("账号不存在，请前往注册");
        }else {
            if(userList.size()>1){
                throw  new UsernameNotFoundException("账号信息异常，请联系管理员");
            }else {
                Collection<GrantedAuthority> authorities=new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(userList.get(0).getRole()));
                authorities.add(new SimpleGrantedAuthority(userList.get(0).getRole()));
               return new org.springframework.security.core.userdetails.User(userList.get(0).getUsername(),
                       userList.get(0).getPassword(),authorities);
            }
        }
    }
}
